﻿using System;
using System.Collections.Generic;

using System.Text;

namespace MSL.Utility.Format
{
    /// <summary>
    /// 格式化类
    /// </summary>
    public class Helper
    {
        #region 格式化时间
        /// <summary>        
        /// 格式化显示时间为几个月,几天前,几小时前,几分钟前,或几秒前；
        /// 此方法多用在发帖，回帖，最新评论，活动等有传达时效性的模块上
        /// </summary>
        /// <param name="dt">要格式化显示的时间</param>
        /// <returns>几个月,几天前,几小时前,几分钟前,或几秒前</returns>        
        public static string DateFromNow(DateTime dt)
        {
            TimeSpan span = DateTime.Now - dt;
            if (span.TotalDays > 60) { return dt.ToShortDateString(); }
            else if (span.TotalDays > 30) { return "1个月前"; }
            else if (span.TotalDays > 14) { return "2周前"; }
            else if (span.TotalDays > 7) { return "1周前"; }
            else if (span.TotalDays > 1) { return String.Format("{0}天前", (int)Math.Floor(span.TotalDays)); }
            else if (span.TotalHours > 1) { return String.Format("{0}小时前", (int)Math.Floor(span.TotalHours)); }
            else if (span.TotalMinutes > 1) { return String.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes)); }
            else if (span.TotalSeconds >= 1) { return String.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds)); }
            else { return "1秒前"; }
        }
        #endregion

        #region 格式化空间大小
        /// <summary>
        /// 格式化占用空间大小的输出
        /// </summary>
        /// <param name="size">大小</param>
        /// <returns>返回 String</returns>
        public static string FormatNUM(long size)
        {
            decimal num;
            string strResult;

            if (size > 1073741824)
            {
                num = (System.Convert.ToDecimal(size) / System.Convert.ToDecimal(1073741824));
                strResult = num.ToString("N") + " M";
            }
            else if (size > 1048576)
            {
                num = (System.Convert.ToDecimal(size) / System.Convert.ToDecimal(1048576));
                strResult = num.ToString("N") + " M";
            }
            else if (size > 1024)
            {
                num = (System.Convert.ToDecimal(size) / System.Convert.ToDecimal(1024));
                strResult = num.ToString("N") + " KB";
            }
            else
            {
                strResult = size + " 字节";
            }

            return strResult;
        }
        #endregion
    }
}
